<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>羊了个羊简单版</title>
  <meta name="theme-color" content="#1a2a6c">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      min-height: 100vh;
      min-height: -webkit-fill-available;
      background: url('http://cdn.yhxweb.cn/bizhi/1721007095-589488-20240222042738170854725857886.jpg') center/cover no-repeat fixed;
      perspective: 1000px;
      display: flex;
      flex-direction: column;
      align-items: center;
      font-family: Arial, sans-serif;
      padding: 10px;
      box-sizing: border-box;
      overflow: hidden;
    }

    .game-container {
      width: 100%;
      max-width: 600px;
      height: 100vh;
      margin: 0 auto;
      padding: 10px;
      display: flex;
      flex-direction: column;
      gap: 10px;
      padding-top: 180px;
      padding-bottom: 120px;
    }

    .game-board {
      position: relative;
      width: 100%;
      flex: 1;
      max-height: 60vh;
      min-height: 40vh;
      background: rgba(255, 255, 255, 0.15);
      backdrop-filter: blur(10px);
      border: 1px solid rgba(255, 255, 255, 0.2);
      border-radius: 15px;
      overflow: hidden;
      margin: auto 0;
    }

    .card {
      position: absolute;
      width: 50px;
      height: 50px;
      min-width: 40px;
      min-height: 40px;
      max-width: 60px;
      max-height: 60px;
      background: rgba(255, 255, 255, 0.95);
      border: 2px solid rgba(255, 255, 255, 0.3);
      border-radius: 12px;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      transform-style: preserve-3d;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
      backdrop-filter: blur(5px);
    }

    .card:hover {
      transform: scale(1.1) translateZ(20px);
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
    }

    .card.selected {
      transform: scale(1.1) translateZ(30px) rotateY(10deg);
      box-shadow: 0 12px 30px rgba(76, 175, 80, 0.3);
      border: 2px solid rgba(76, 175, 80, 0.6);
    }

    .score-board {
      position: fixed;
      top: 140px;
      left: 50%;
      transform: translateX(-50%);
      background: rgba(255, 255, 255, 0.3);
      backdrop-filter: blur(10px);
      padding: 8px 15px;
      border-radius: 20px;
      color: white;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
      font-size: 16px;
      z-index: 99;
      border: 1px solid rgba(255, 255, 255, 0.4);
    }

    .selected-container {
      position: fixed;
      bottom: 20px;
      left: 0;
      right: 0;
      background: rgba(255, 255, 255, 0.3);
      backdrop-filter: blur(10px);
      border-top: 2px solid rgba(255, 255, 255, 0.4);
      padding: 15px 10px;
      display: flex;
      gap: 10px;
      justify-content: center;
      align-items: center;
      z-index: 100;
      height: 90px;
      box-shadow: 0 -4px 15px rgba(0, 0, 0, 0.1);
    }

    .restart-btn {
      background: linear-gradient(45deg, #4CAF50, #45a049);
      box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3);
      transform: translateZ(10px);
      transition: all 0.3s ease;
      text-transform: uppercase;
      letter-spacing: 1px;
      font-weight: bold;
      margin-top: 10px;
      padding: 8px 15px;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 14px;
    }

    .restart-btn:hover {
      transform: translateZ(15px) scale(1.05);
      box-shadow: 0 8px 25px rgba(76, 175, 80, 0.4);
      background: linear-gradient(45deg, #45a049, #4CAF50);
    }

    /* 添加图标颜色样式 */
    .card[data-icon="fa-heart"] i {
      color: #e91e63;
    }

    .card[data-icon="fa-star"] i {
      color: #ffc107;
    }

    .card[data-icon="fa-cloud"] i {
      color: #03a9f4;
    }

    .card[data-icon="fa-moon"] i {
      color: #673ab7;
    }

    .card[data-icon="fa-sun"] i {
      color: #ff9800;
    }

    .card[data-icon="fa-bell"] i {
      color: #795548;
    }

    .card[data-icon="fa-gift"] i {
      color: #e91e63;
    }

    .card[data-icon="fa-leaf"] i {
      color: #4caf50;
    }

    .card[data-icon="fa-car"] i {
      color: #607d8b;
    }

    .card[data-icon="fa-home"] i {
      color: #9c27b0;
    }

    /* 添加加载动画样式 */
    #loadingScreen {
      background: url('http://cdn.yhxweb.cn/bizhi/1721007095-589488-20240222042738170854725857886.jpg') center/cover no-repeat fixed;
      position: fixed;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
      height: -webkit-fill-available;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      z-index: 9999;
    }

    .progress-bar {
      background: rgba(255, 255, 255, 0.1);
      border-radius: 10px;
      overflow: hidden;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
      width: 200px;
      height: 4px;
      margin: 10px 0;
    }

    .progress {
      background: linear-gradient(45deg, #4CAF50, #45a049);
      box-shadow: 0 2px 10px rgba(76, 175, 80, 0.3);
      width: 0%;
      height: 100%;
      transition: width 0.3s ease;
    }

    .loading-text {
      color: white;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
      font-size: 16px;
      letter-spacing: 1px;
      margin-top: 10px;
    }

    .selected-slot {
      width: 50px;
      height: 50px;
      min-width: 40px;
      min-height: 40px;
      max-width: 60px;
      max-height: 60px;
      background: rgba(255, 255, 255, 0.1);
      border: 2px dashed rgba(255, 255, 255, 0.3);
      transition: all 0.3s ease;
      transform-style: preserve-3d;
      border-radius: 8px;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
    }

    .slot-card {
      transform-style: preserve-3d;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
      position: absolute;
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #ffffff;
      border: 2px solid #e0e0e0;
      border-radius: 8px;
    }

    .card.moving {
      transition: all 0.3s ease;
      pointer-events: none;
    }

    .level-info {
      background: rgba(255, 255, 255, 0.15);
      backdrop-filter: blur(8px);
      border: 1px solid rgba(255, 255, 255, 0.2);
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
      transform: translateZ(20px);
      position: absolute;
      top: 20px;
      left: 20px;
      font-size: 18px;
      color: #333;
      background: rgba(255, 255, 255, 0.9);
      padding: 10px;
      border-radius: 5px;
    }

    .next-level-modal {
      background: rgba(255, 255, 255, 0.95);
      backdrop-filter: blur(15px);
      border: 1px solid rgba(255, 255, 255, 0.3);
      box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
      transform: translate(-50%, -50%) translateZ(50px);
      animation: modalPop 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: white;
      padding: 15px;
      border-radius: 10px;
      text-align: center;
      z-index: 1000;
      display: none;
      width: 90%;
      max-width: 300px;
    }

    .next-level-btn {
      width: 100%;
      padding: 10px;
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      margin-top: 10px;
    }

    @keyframes fadeIn {
      from {
        opacity: 0;
        transform: translateY(20px) translateZ(-50px);
      }

      to {
        opacity: 1;
        transform: translateY(0) translateZ(0);
      }
    }

    @keyframes modalPop {
      from {
        opacity: 0;
        transform: translate(-50%, -50%) scale(0.8) translateZ(50px);
      }

      to {
        opacity: 1;
        transform: translate(-50%, -50%) scale(1) translateZ(50px);
      }
    }

    @keyframes gradientBG {
      0% {
        background-position: 0% 50%;
      }

      50% {
        background-position: 100% 50%;
      }

      100% {
        background-position: 0% 50%;
      }
    }

    /* 修改关卡选择器样式 */
    .level-selector {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: rgba(255, 255, 255, 0.95);
      backdrop-filter: blur(10px);
      border: 1px solid rgba(255, 255, 255, 0.2);
      padding: 20px;
      border-radius: 15px;
      width: 90%;
      max-width: 300px;
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      justify-content: center;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
      z-index: 1000;
      animation: modalPop 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
    }

    /* 添加遮罩层 */
    .modal-overlay {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      backdrop-filter: blur(3px);
      z-index: 999;
      opacity: 0;
      visibility: hidden;
      transition: all 0.3s ease;
    }

    .modal-overlay.active {
      opacity: 1;
      visibility: visible;
    }

    /* 修改关卡按钮样式 */
    .level-btn {
      background: rgba(255, 255, 255, 0.9);
      border: 1px solid rgba(0, 0, 0, 0.1);
      padding: 12px 20px;
      border-radius: 10px;
      color: #333;
      cursor: pointer;
      transition: all 0.3s ease;
      min-width: 100px;
      text-align: center;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    }

    .level-btn:hover {
      background: rgba(255, 255, 255, 1);
      transform: translateY(-2px);
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
    }

    .level-btn.active {
      background: #4CAF50;
      color: white;
      border-color: #45a049;
    }

    /* 修改媒体查询适配不同屏幕 */
    @media screen and (max-width: 360px) {
      body {
        padding: 5px;
      }

      .game-container {
        padding: 5px;
      }

      .level-btn {
        padding: 5px 10px;
        font-size: 12px;
      }

      .level-icon {
        width: 25px;
        height: 25px;
      }

      .score-board {
        font-size: 16px;
      }
    }

    /* 修复 iOS Safari 100vh 问题 */
    @supports (-webkit-touch-callout: none) {
      body {
        height: -webkit-fill-available;
      }
    }

    /* 添加悬浮按钮样式 */
    .floating-buttons {
      position: fixed;
      right: 10px;
      top: 40%;
      transform: translateY(-50%);
      display: flex;
      flex-direction: column;
      gap: 15px;
      z-index: 100;
    }

    .float-btn {
      width: 35px;
      height: 35px;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.2);
      backdrop-filter: blur(5px);
      border: 1px solid rgba(255, 255, 255, 0.3);
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      color: white;
      transition: all 0.3s ease;
    }

    .float-btn:hover {
      background: rgba(255, 255, 255, 0.3);
      transform: scale(1.1);
    }

    .float-btn.active {
      background: rgba(76, 175, 80, 0.6);
      border-color: rgba(76, 175, 80, 0.8);
    }

    /* 添加提示文字样式 */
    .float-btn .tooltip {
      position: absolute;
      right: 45px;
      background: rgba(0, 0, 0, 0.8);
      color: white;
      padding: 5px 10px;
      border-radius: 5px;
      font-size: 12px;
      white-space: nowrap;
      opacity: 0;
      visibility: hidden;
      transition: all 0.3s ease;
    }

    .float-btn:hover .tooltip {
      opacity: 1;
      visibility: visible;
    }

    /* 适配小屏幕设备 */
    @media screen and (max-height: 600px) {
      .game-container {
        padding-top: 160px;
        padding-bottom: 100px;
      }

      .game-board {
        max-height: 50vh;
      }

      .selected-container {
        height: 70px;
        bottom: 15px;
      }

      .score-board {
        top: 120px;
      }

      .level-info-container {
        top: 15px;
      }
    }

    /* 适配超小屏幕设备 */
    @media screen and (max-height: 500px) {
      .game-board {
        max-height: 55vh;
      }

      .floating-buttons {
        gap: 10px;
      }

      .float-btn {
        width: 35px;
        height: 35px;
      }
    }

    /* 修改顶部信息容器位置 */
    .level-info-container {
      position: fixed;
      top: 20px;
      left: 50%;
      transform: translateX(-50%);
      padding: 8px 15px;
      border-radius: 20px;
      font-size: 14px;
      z-index: 98;
      background: rgba(255, 255, 255, 0.3);
      backdrop-filter: blur(10px);
      border: 1px solid rgba(255, 255, 255, 0.4);
      color: white;
    }

    /* 在右侧按钮组中添加联系客服按钮样式 */
    .contact-btn {
      position: fixed;
      right: 15px;
      bottom: 180px;
      width: 40px;
      height: 40px;
      background: rgba(255, 255, 255, 0.3);
      backdrop-filter: blur(10px);
      border: 1px solid rgba(255, 255, 255, 0.4);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      color: white;
      font-size: 20px;
      z-index: 99;
    }

    /* 微信二维码弹窗样式 */
    .qrcode-modal {
      display: none;
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: white;
      padding: 20px;
      border-radius: 10px;
      z-index: 1000;
      text-align: center;
    }

    .qrcode-modal img {
      width: 200px;
      height: 200px;
      margin-bottom: 10px;
    }

    .qrcode-modal p {
      margin: 0;
      color: #333;
      font-size: 14px;
    }

    .modal-overlay {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      z-index: 999;
    }

    .card,
    .slot-card {
      transition: all 0.3s ease;
      will-change: transform, opacity;
    }

    .card.removing,
    .slot-card.removing {
      pointer-events: none;
      z-index: -1;
    }
  </style>
  <!-- 添加多个备 CDN 源 -->
  <link rel="preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" />
  <link rel="preload" as="style" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.0.0/css/all.min.css" />
</head>

<body>
  <!-- 添加加载屏幕 -->
  <div id="loadingScreen">
    <div class="progress-bar">
      <div id="progressBar" class="progress"></div>
    </div>
    <div class="loading-text">游戏加载中...</div>
  </div>

  <!-- 在 game-container 之前添加关卡选择器和信息 -->
  <div class="level-selector" id="levelSelector" style="display: none;">
    <!-- 关卡按钮会通过 JS 动态生成 -->
  </div>

  <div class="level-info-container">
    <div>
      <div>当前关卡：第 <span id="currentLevelDisplay">1</span> 关</div>
      <div>总分：<span id="totalScoreDisplay">0</span></div>
    </div>
  </div>

  <!-- 有游戏内容 -->
  <div class="game-container" style="display: none;" id="gameContainer">
    <div class="score-board">分数: <span id="score">0</span></div>
    <div class="game-board" id="gameBoard"></div>
    <div class="selected-container" id="selectedContainer"></div>
  </div>

  <div class="next-level-modal" id="levelModal">
    <h2>恭喜通关！</h2>
    <p>当前得分: <span id="modalScore">0</span></p>
    <button class="next-level-btn" onclick="startNextLevel()">进入下一关</button>
  </div>

  <div class="floating-buttons">
    <div class="float-btn" onclick="toggleLevelSelect()" id="levelSelectBtn">
      <i class="fas fa-list"></i>
      <span class="tooltip">选择关卡</span>
    </div>
    <div class="float-btn" onclick="restartCurrentLevel()">
      <i class="fas fa-redo"></i>
      <span class="tooltip">重新开始本关</span>
    </div>
    <div class="float-btn" onclick="restartGame()">
      <i class="fas fa-home"></i>
      <span class="tooltip">返回首页</span>
    </div>
  </div>

  <!-- 添加遮罩层 -->
  <div class="modal-overlay" id="levelOverlay"></div>

  <!-- <div class="contact-btn" onclick="showQRCode()">
    <i class="fas fa-comments"></i>
  </div> -->

  <div class="modal-overlay" id="modalOverlay" onclick="hideQRCode()"></div>
  <div class="qrcode-modal" id="qrcodeModal" onclick="hideQRCode()">
    <img src="http://cdn.yhxweb.cn/yuelao/img/my_code.jpg" alt="微信二维码">
    <p>扫码添加客服微信</p>
  </div>

  <script>
    const icons = [
      'fa-heart', 'fa-star', 'fa-cloud', 'fa-moon', 'fa-sun',
      'fa-bell', 'fa-gift', 'fa-leaf', 'fa-car', 'fa-home'
    ];

    let score = 0;
    let selectedCards = [];
    let cards = [];

    // 添加新变量
    const MAX_LAYERS = 3; // 最大压住数

    function createCard(icon, index) {
      const card = document.createElement('div');
      card.className = 'card';
      card.innerHTML = `<i class="fas ${icon} fa-2x"></i>`;
      card.dataset.icon = icon;
      card.dataset.index = index;
      card.dataset.layer = 0;

      // 修改随机位置计算
      const gameBoard = document.getElementById('gameBoard');
      const cardWidth = 60; // 使用固定值计算位置
      const cardHeight = 60;
      const maxLeft = gameBoard.offsetWidth - cardWidth;
      const maxTop = gameBoard.offsetHeight - cardHeight;

      // 确保卡片完全在游戏板内
      const left = Math.max(0, Math.min(maxLeft, Math.random() * maxLeft));
      const top = Math.max(0, Math.min(maxTop, Math.random() * maxTop));

      card.style.left = `${left}px`;
      card.style.top = `${top}px`;

      card.addEventListener('click', () => selectCard(card));
      return card;
    }

    function initializeGame() {
      const gameBoard = document.getElementById('gameBoard');
      gameBoard.innerHTML = '';
      cards = [];
      selectedCards = [];
      score = 0;
      document.getElementById('score').textContent = score;

      // 创建卡片对（每个图标出3次）
      const gameIcons = [];
      icons.forEach(icon => {
        for (let i = 0; i < 3; i++) {
          gameIcons.push(icon);
        }
      });

      // 打乱图标顺序
      for (let i = gameIcons.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [gameIcons[i], gameIcons[j]] = [gameIcons[j], gameIcons[i]];
      }

      // 创建卡片
      gameIcons.forEach((icon, index) => {
        const card = createCard(icon, index);
        gameBoard.appendChild(card);
        cards.push(card);
      });

      // 初始化卡槽
      const selectedContainer = document.getElementById('selectedContainer');
      selectedContainer.innerHTML = '';
      for (let i = 0; i < 6; i++) {
        const slot = document.createElement('div');
        slot.className = 'selected-slot';
        slot.dataset.slotIndex = i;
        selectedContainer.appendChild(slot);
      }
    }

    function selectCard(card) {
      const layer = getCardLayer(card);

      // 如果被3层或以上相同类型的卡片压住，则不能选择
      if (layer >= 3) {
        card.style.animation = 'shake 0.5s ease';
        setTimeout(() => {
          card.style.animation = '';
        }, 500);
        return;
      }

      if (selectedCards.length < 6 && !selectedCards.includes(card)) {
        card.classList.add('selected');
        selectedCards.push(card);
        moveToSlot(card, selectedCards.length - 1);

        // 检查是否已满6个卡槽
        if (selectedCards.length === 6) {
          // 立即检查是否有可消除的组合
          const cardGroups = {};
          selectedCards.forEach(c => {
            const icon = c.dataset.icon;
            if (!cardGroups[icon]) {
              cardGroups[icon] = [];
            }
            cardGroups[icon].push(c);
          });

          // 检查是否有三个相同的卡片
          const hasMatch = Object.values(cardGroups).some(group => group.length >= 3);

          if (!hasMatch) {
            // 如果没有可消除的组合，游戏失败
            setTimeout(() => {
              alert('游戏失败！卡槽已满，且没有可消除的组合。');
              restartCurrentLevel();
            }, 300);
          } else {
            // 有可消除的组合，执行消除
            checkMatch();
          }
        } else {
          // 未满6个卡槽时，仍然检查是否有可消除的组合
          const cardGroups = {};
          selectedCards.forEach(c => {
            const icon = c.dataset.icon;
            if (!cardGroups[icon]) {
              cardGroups[icon] = [];
            }
            cardGroups[icon].push(c);
          });

          if (Object.values(cardGroups).some(group => group.length >= 3)) {
            checkMatch();
          }
        }
      }
    }

    function getCardLayer(card) {
      const rect1 = card.getBoundingClientRect();
      let layer = 0;
      const cardIcon = card.dataset.icon;

      // 获取所在这张卡上面的卡片
      cards.forEach(otherCard => {
        if (otherCard !== card && !otherCard.classList.contains('selected') && otherCard.style.opacity !== '0') {
          const rect2 = otherCard.getBoundingClientRect();
          // 检查是否重叠且是否是相同类型的卡片
          if (isOverlapping(rect1, rect2) && otherCard.dataset.icon === cardIcon) {
            layer++;
          }
        }
      });

      return layer;
    }

    function isOverlapping(rect1, rect2) {
      return !(rect1.right < rect2.left ||
        rect1.left > rect2.right ||
        rect1.bottom < rect2.top ||
        rect1.top > rect2.bottom);
    }

    function moveToSlot(card, slotIndex) {
      const selectedContainer = document.getElementById('selectedContainer');
      const slots = selectedContainer.getElementsByClassName('selected-slot');

      // 检查��槽否已满
      if (slotIndex >= slots.length) {
        alert('游戏失败！卡槽已满，无法继续游戏。');
        restartGame();
        return;
      }

      const slot = slots[slotIndex];
      const slotRect = slot.getBoundingClientRect();
      const cardRect = card.getBoundingClientRect();

      // 创建一个克隆卡片用于动画
      const clone = card.cloneNode(true);
      clone.style.position = 'fixed';
      clone.style.left = cardRect.left + 'px';
      clone.style.top = cardRect.top + 'px';
      clone.classList.add('moving');
      document.body.appendChild(clone);

      // 隐藏原卡片
      card.style.visibility = 'hidden';

      // 执行移动动画
      requestAnimationFrame(() => {
        clone.style.left = slotRect.left + 'px';
        clone.style.top = slotRect.top + 'px';
      });

      // 动画结束后在卡槽中创建永久卡片
      setTimeout(() => {
        clone.remove();

        // 在卡槽中创建永久卡片
        const slotCard = document.createElement('div');
        slotCard.className = 'slot-card';
        slotCard.innerHTML = card.innerHTML;
        slotCard.dataset.icon = card.dataset.icon;
        slot.appendChild(slotCard);
      }, 300);
    }

    function checkMatch() {
      const cardGroups = {};
      selectedCards.forEach(card => {
        const icon = card.dataset.icon;
        if (!cardGroups[icon]) {
          cardGroups[icon] = [];
        }
        cardGroups[icon].push(card);
      });

      // 找到三个相同的卡片组
      const matchedGroup = Object.values(cardGroups).find(group => group.length >= 3);

      if (matchedGroup) {
        // 禁用点击事件，防止动画过程中的交互
        document.querySelectorAll('.card').forEach(card => {
          card.style.pointerEvents = 'none';
        });

        // 获取所有需要移除的元素
        const slots = document.getElementsByClassName('selected-slot');
        const matchedIndices = matchedGroup.map(card => selectedCards.indexOf(card));

        // 标记所有要移除的卡片
        matchedGroup.forEach(card => {
          card.classList.add('removing');
          card.style.transform = 'scale(0)';
          card.style.opacity = '0';
        });

        // 标记所有要移除的卡槽卡片
        matchedIndices.forEach(index => {
          if (index !== -1 && slots[index]) {
            const slotCard = slots[index].querySelector('.slot-card');
            if (slotCard) {
              slotCard.classList.add('removing');
              slotCard.style.transform = 'scale(0)';
              slotCard.style.opacity = '0';
            }
          }
        });

        // 等待动画完成后清理元素
        setTimeout(() => {
          // 移除游戏板上的卡片
          document.querySelectorAll('.card.removing').forEach(card => {
            card.remove();
          });
          cards = cards.filter(card => !card.classList.contains('removing'));

          // 移除卡槽中的卡片
          document.querySelectorAll('.slot-card.removing').forEach(slotCard => {
            slotCard.remove();
          });

          // 更新选中卡片数组
          selectedCards = selectedCards.filter(card => !matchedGroup.includes(card));

          // 重新启用点击事件
          document.querySelectorAll('.card').forEach(card => {
            card.style.pointerEvents = 'auto';
          });

          // 更新分数
          score += 10;
          document.getElementById('score').textContent = score;

          // 检查游戏是否结束
          if (cards.length === 0) {
            checkGameWin();
          }
        }, 300);
      }
    }

    function restartGame() {
      initializeGame();
    }

    // 定义多个CDN源
    const CDN_URLS = [
      'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css',
      'https://cdn.bootcdn.net/ajax/libs/font-awesome/6.0.0/css/all.min.css',
      'https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.0.0/css/all.min.css'
    ];

    // 修改资源加载函数
    function loadResources() {
      return new Promise((resolve) => {
        let currentCDNIndex = 0;
        const progressBar = document.getElementById('progressBar');
        const loadingScreen = document.getElementById('loadingScreen');
        const gameContainer = document.getElementById('gameContainer');
        let progress = 0;

        const updateProgress = (value) => {
          progress = value;
          progressBar.style.width = `${progress}%`;
        };

        const tryLoadFont = () => {
          if (currentCDNIndex >= CDN_URLS.length) {
            // 所有CDN都失败，使用内置图标
            useFallbackIcons();
            return;
          }

          const fontAwesome = document.createElement('link');
          fontAwesome.rel = 'stylesheet';
          fontAwesome.href = CDN_URLS[currentCDNIndex];

          const loadingInterval = setInterval(() => {
            if (progress < 70) {
              updateProgress(progress + 1);
            }
          }, 20);

          fontAwesome.onload = () => {
            clearInterval(loadingInterval);
            updateProgress(100);
            setTimeout(() => {
              loadingScreen.style.display = 'none';
              gameContainer.style.display = 'block';
              initializeGame();
              resolve();
            }, 500);
          };

          fontAwesome.onerror = () => {
            clearInterval(loadingInterval);
            currentCDNIndex++;
            document.head.removeChild(fontAwesome);
            tryLoadFont();
          };

          document.head.appendChild(fontAwesome);
        };

        // 使用备用图标的函数
        function useFallbackIcons() {
          // 用 Unicode 字符作为备用图标
          const fallbackIcons = {
            'fa-heart': '❤️',
            'fa-star': '⭐',
            'fa-cloud': '☁️',
            'fa-moon': '🌙',
            'fa-sun': '☀️',
            'fa-bell': '🔔',
            'fa-gift': '🎁',
            'fa-leaf': '🍃',
            'fa-car': '🚗',
            'fa-home': '🏠'
          };

          // 修改创建卡片的函数
          window.createCard = function (icon, index) {
            const card = document.createElement('div');
            card.className = 'card';
            card.innerHTML = fallbackIcons[icon];
            card.dataset.icon = icon;
            card.dataset.index = index;

            const left = Math.random() * (gameBoard.offsetWidth - 60);
            const top = Math.random() * (gameBoard.offsetHeight - 60);
            card.style.left = `${left}px`;
            card.style.top = `${top}px`;

            card.style.fontSize = '24px'; // 调整 emoji 大小
            card.addEventListener('click', () => selectCard(card));
            return card;
          };

          updateProgress(100);
          setTimeout(() => {
            loadingScreen.style.display = 'none';
            gameContainer.style.display = 'block';
            initializeGame();
            resolve();
          }, 500);
        }

        // 开始尝试载
        tryLoadFont();
      });
    }

    // 修改游戏初始化函数
    async function startGame() {
      await loadResources();
      initializeLevelSelector();
      initializeGame(0);
    }

    // 启动游戏
    startGame();

    // 扩图标库
    const ALL_ICONS = [
      // 基础图标
      'fa-heart', 'fa-star', 'fa-cloud', 'fa-moon', 'fa-sun',
      'fa-bell', 'fa-gift', 'fa-leaf', 'fa-car', 'fa-home',
      // 进阶图标
      'fa-fish', 'fa-cat', 'fa-dog', 'fa-dragon', 'fa-dove',
      'fa-horse', 'fa-hippo', 'fa-frog', 'fa-spider', 'fa-kiwi-bird',
      // 高级图标
      'fa-ghost', 'fa-robot', 'fa-rocket', 'fa-guitar', 'fa-umbrella',
      'fa-crown', 'fa-dice', 'fa-chess-king', 'fa-gem', 'fa-anchor'
    ];

    // 关卡配置
    const LEVELS = [
      {
        icons: 8,        // 使用图标数量
        totalCards: 24,  // 总卡片数量
        maxLayers: 3,    // 最大压住层数
        slots: 6
      },
      {
        icons: 10,
        totalCards: 36,  // 增加卡片总数
        maxLayers: 4,
        slots: 6
      },
      {
        icons: 12,
        totalCards: 48,  // 更多卡片
        maxLayers: 4,
        slots: 6
      },
      {
        icons: 15,
        totalCards: 60,  // 大量卡片
        maxLayers: 5,
        slots: 6
      },
      {
        icons: 18,
        totalCards: 72,  // 最多卡片
        maxLayers: 5,
        slots: 6
      }
    ];

    let currentLevel = 0;
    let totalScore = 0;

    // 修改初始化游戏函数
    function initializeGame(levelIndex = 0) {
      currentLevel = levelIndex;
      const level = LEVELS[currentLevel];
      const gameBoard = document.getElementById('gameBoard');
      gameBoard.innerHTML = '';

      cards = [];
      selectedCards = [];
      score = 0;
      document.getElementById('score').textContent = totalScore;
      updateLevelInfo();

      // 创建卡片
      const gameIcons = [];
      const levelIcons = ALL_ICONS.slice(0, level.icons);

      // 计算每个图标至少需要出现的次数（确保可以消除）
      const minRepeat = 3;
      const remainingSlots = level.totalCards - (levelIcons.length * minRepeat);
      const extraRepeats = Math.floor(remainingSlots / levelIcons.length);

      // 先确保每个图标至少出现3次
      levelIcons.forEach(icon => {
        for (let i = 0; i < minRepeat; i++) {
          gameIcons.push(icon);
        }
        // 随机添加额外的重复
        for (let i = 0; i < extraRepeats; i++) {
          gameIcons.push(icon);
        }
      });

      // 如果还有剩余的卡槽位，随机填充
      const remaining = level.totalCards - gameIcons.length;
      for (let i = 0; i < remaining; i++) {
        const randomIcon = levelIcons[Math.floor(Math.random() * levelIcons.length)];
        gameIcons.push(randomIcon);
      }

      // 打乱图标顺序
      shuffleArray(gameIcons);

      // 创建卡片并添加到游戏板
      gameIcons.forEach((icon, index) => {
        const card = createCard(icon, index);
        gameBoard.appendChild(card);
        cards.push(card);
      });

      // 初始化卡槽
      const selectedContainer = document.getElementById('selectedContainer');
      selectedContainer.innerHTML = '';
      for (let i = 0; i < level.slots; i++) {
        const slot = document.createElement('div');
        slot.className = 'selected-slot';
        slot.dataset.slotIndex = i;
        selectedContainer.appendChild(slot);
      }
    }

    // 添加数组随机排序函数
    function shuffleArray(array) {
      for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
      }
      return array;
    }

    // 修改游戏胜利检查
    function checkGameWin() {
      if (document.querySelectorAll('.card').length === 0) {
        totalScore += score;
        if (currentLevel < LEVELS.length - 1) {
          // 显示下一关对话框
          const modal = document.getElementById('levelModal');
          document.getElementById('modalScore').textContent = totalScore;
          modal.style.display = 'block';
        } else {
          // 通关
          alert(`恭喜你通关了！\n总分：${totalScore}`);
          currentLevel = 0;
          totalScore = 0;
          initializeGame();
        }
      }
    }

    // 添加进入下一关函数
    function startNextLevel() {
      document.getElementById('levelModal').style.display = 'none';
      currentLevel++;
      initializeLevelSelector(); // 更新关卡选择器
      initializeGame(currentLevel);
    }

    // 修改重新开始函数
    function restartGame() {
      currentLevel = 0;
      totalScore = 0;
      initializeGame();
    }

    // 添加重启当前关卡的函数
    function restartCurrentLevel() {
      // 保持当前关卡不变，只重置游戏状态
      score = 0;
      document.getElementById('score').textContent = score;
      initializeGame(currentLevel);
    }

    // 添加初始化关卡选择器函数
    function initializeLevelSelector() {
      const levelSelector = document.getElementById('levelSelector');
      levelSelector.innerHTML = '';

      LEVELS.forEach((level, index) => {
        const btn = document.createElement('div');
        btn.className = 'level-btn' + (index === currentLevel ? ' active' : '');
        btn.textContent = `第 ${index + 1} 关`;
        btn.onclick = () => selectLevel(index);
        levelSelector.appendChild(btn);
      });
    }

    // 修改关卡选择函数
    function selectLevel(levelIndex) {
      if (levelIndex !== currentLevel) {
        currentLevel = levelIndex;
        totalScore = 0;
        updateLevelInfo();
        initializeGame(levelIndex);

        // 更新关卡按钮状态
        const buttons = document.querySelectorAll('.level-btn');
        buttons.forEach((btn, idx) => {
          btn.classList.toggle('active', idx === levelIndex);
        });
      }

      // 关闭关卡选择器
      document.getElementById('levelSelector').style.display = 'none';
      document.getElementById('levelOverlay').classList.remove('active');
      document.getElementById('levelSelectBtn').classList.remove('active');
    }

    // 简化更新关卡信息函数
    function updateLevelInfo() {
      document.getElementById('currentLevelDisplay').textContent = currentLevel + 1;
      document.getElementById('totalScoreDisplay').textContent = totalScore;
    }

    // 添加切换关卡选择器显的函数
    function toggleLevelSelect() {
      const levelSelector = document.getElementById('levelSelector');
      const levelOverlay = document.getElementById('levelOverlay');
      const levelSelectBtn = document.getElementById('levelSelectBtn');

      if (levelSelector.style.display === 'none') {
        levelSelector.style.display = 'flex';
        levelOverlay.classList.add('active');
        levelSelectBtn.classList.add('active');
      } else {
        levelSelector.style.display = 'none';
        levelOverlay.classList.remove('active');
        levelSelectBtn.classList.remove('active');
      }
    }

    // 添加点击遮罩层关闭选择器
    document.getElementById('levelOverlay').addEventListener('click', function () {
      toggleLevelSelect();
    });

    function showQRCode() {
      document.getElementById('modalOverlay').style.display = 'block';
      document.getElementById('qrcodeModal').style.display = 'block';
    }

    function hideQRCode() {
      document.getElementById('modalOverlay').style.display = 'none';
      document.getElementById('qrcodeModal').style.display = 'none';
    }
  </script>
  <!-- 添加Font Awesome图标库 -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
</body>

</html>